<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { supplierSelector } from "@/services/goods";
// import { appStockQuery } from "@/services/transfer.js";
import { operation } from "@/utils/num.js";
// import { appStockQuery } from "@/services/transfer.js";
import { PlanProduct } from "@/services/requiregoods.js";

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const code = ref("");
const payNum = ref(0);
const id = ref("");
const topHeight = ref(uni.getStorageSync("topHight") || 0);
const supplierId = ref("");

onLoad((option) => {
  id.value = option.id ? option.id : "";
  supplierId.value = option.supplierId ? option.supplierId : "";
  code.value = option.code ? option.code : "";
  form.value.keyword = option.code ? option.code : "";
  if (uni.getStorageSync("goodsSel")) {
    selectNumList.value = JSON.parse(uni.getStorageSync("goodsSel"));
    selectNumList.value.forEach((item) => {
      payNum.value = payNum.value + item.transferNum;
      // payPrice.value = operation(
      //   payPrice.value,
      //   operation(item.transferNum, item.taxPrice, 2, "multiply"),
      //   2,
      //   "add"
      // );
    });
    getNum();
  }

  getAppShopSelector();
  if (!supplierId.value) {
    getappStockQuery();
  }
  // if (uni.getStorageSync("shopselect")) {
  //   selectShopObj.value = JSON.parse(uni.getStorageSync("shopselect"));
  // }
});

const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getappStockQuery(1);
};
const isShowBtn = ref(true);
const searchFun = (val) => {
  console.log("取2消");
  form.value.keyword = val;
  loading.value = "";
  console.log(form.value.name);
  getappStockQuery(1);
};
const focusFun = () => {
  isShowBtn.value = false;
};
const blurFun = () => {
  isShowBtn.value = true;
};

onReachBottom(() => {
  console.log("触底了");
  getappStockQuery();
});
onMounted(() => {});

//获取商品
const form = ref({
  categoryId: "",
  pageIndex: 1,
  pageSize: 99999,
  barCode: "",
  code: "",
  name: "",
  skuCode: "",
  categoryId: "",
  available: "",
  keyword: "",
  supplierId: "",
});

const goodsNum = ref(0);
const payPrice = ref(0);

const productData = ref([]);

const loading = ref("");
const getappStockQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await PlanProduct(form.value);
    if (res.code == 200) {
      if (res.data) {
        res.data.forEach((element) => {
          let ifHave = false;
          selectNumList.value.forEach((item) => {
            if (element.id == item.id) {
              ifHave = true;
              element.transferNum = item.transferNum;
            }
          });
          if (!ifHave) {
            element.transferNum = 0;
          }
        });
        productData.value = productData.value.concat(res.data);
        console.log(productData.value);
        form.value.pageIndex = form.value.pageIndex + 1;

        if (res.data.length < form.value.pageSize) {
          loading.value = "noMore";
        } else {
          loading.value = "More";
        }
      } else {
        productData.value = "";
        loading.value = "noMore";
      }
    } else {
    }

    console.log(res);
  } catch (e) {
    console.log(e);
  }
};
function getNum() {
  let num = 0;
  selectNumList.value.forEach((item) => {
    num += item.transferNum;
    console.log(item.transferNum, "num");
  });
  goodsNum.value = num;
}
const selectNumList = ref([]);
const selectItem = ref({});
const showMode = ref(false);
const showIndex = ref(0);
const showTwoIndex = ref(0);
const onClickMinus = (item, index) => {
  // if (item.stockNum <= 0) {
  //   uni.showToast({
  //     title: "库存不足",
  //     icon: "none",
  //   });
  //   return;
  // }
  selectItem.value = item;
  showIndex.value = index;

  showTwoIndex.value = selectNumList.value.length;
  item.transferNum = item.transferNum + 1;
  if (item.transferNum > item.stockNum) {
    showMode.value = true;
  }

  if (selectNumList.value <= 0) {
    selectNumList.value.push(item);
    getNum();
    return;
  }
  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == item.id) {
      isnew = false;
      selectNumList.value[index1] = item;
    }
  });
  if (isnew) {
    selectNumList.value.push(item);
  }
  getNum();
  uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));

  // selectNumList.value = [...selectNumList.value, ...[item]];
};
const valChange = (item, index, e) => {
  selectItem.value = item;
  showIndex.value = index;

  if (e.value > item.stockNum) {
    // showMode.value = true;
  }

  if (selectNumList.value <= 0) {
    selectNumList.value.push(item);
    getNum();

    uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));

    return;
  }
  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == item.id) {
      showTwoIndex.value = index1;
      selectNumList.value[index1] = item;
      isnew = false;
    }
  });
  if (isnew) {
    showTwoIndex.value = selectNumList.value.length;
    selectNumList.value.push(item);
  }

  setTimeout(() => {
    selectNumList.value.forEach((item, index) => {
      if (item.transferNum <= 0) {
        selectNumList.value.splice(index, 1);
      }
    });
    getNum();

    uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));
  }, 100);
};

const blurChange = (item, index, e) => {
  if (e.value == "") {
    item.transferNum = 0;
  }
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/goods/goods_add/index?id=" + item.id });
};

const cancelFun = () => {
  showMode.value = false;
  productData.value[showIndex.value].transferNum =
    productData.value[showIndex.value].stockNum;

  selectNumList.value[showTwoIndex.value].transferNum =
    selectNumList.value[showTwoIndex.value].stockNum;

  getNum();
};
const confirmFun = () => {
  showMode.value = false;
};
//改价列表
const goRecord = () => {
  // selectNumList.value.forEach((item, index) => {
  //   if (item.transferNum <= 0) {
  //     selectNumList.value.splice(index, 1);
  //   }
  // });
  if (selectNumList.value.length <= 0) {
    uni.showToast({
      title: "请先选择商品",
      icon: "none",
    });
    return;
  }

  uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));

  uni.navigateTo({
    url: "/pages/require_goods/goods_swith/index?id=" + id.value,
  });
};

//商品选择
const showSelect = ref(false);

const onClickItem = (item, index) => {
  console.log(item, index);
  selectItem.value = item;
  showIndex.value = index;

  showTwoIndex.value = selectNumList.value.length;
  item.transferNum = item.transferNum;
  if (item.transferNum > item.stockNum) {
    showMode.value = true;
  }

  if (selectNumList.value <= 0) {
    selectNumList.value.push(item);
    getNum();
    showSelect.value = true;
    return;
  }
  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == item.id) {
      isnew = false;
      selectNumList.value[index1] = item;
    }
  });
  if (isnew) {
    selectNumList.value.push(item);
  }
  getNum();
  showSelect.value = true;
};

// 供应商选择模块
const ShopList = ref([]);
const showInShop = ref(false);
const selectid = ref("");
const supplierName = ref("");
// showInShop.value = false;
// 门店选择
const shopSelectShow = () => {
  showInShop.value = true;
};

const getAppShopSelector = async () => {
  let res = await supplierSelector({ pageIndex: 1, pageSize: 99999 });

  ShopList.value = res.data.datas;
  // selectShopObj.value.targetShopId = ShopList.value[0].id;
  // selectShopObj.value.targetShopName = ShopList.value[0].name;
  console.log("供应商选择", supplierId.value);
  if (!supplierId.value) {
    return;
  }
  res.data.datas.forEach((item, index) => {
    if (item.id == supplierId.value) {
      selectid.value = item.id;
      supplierName.value = item.name;
      form.value.supplierId = selectid.value;
      getappStockQuery();
    }
  });
};
// const selectItem = ref({});
const shopSelect = (e) => {
  console.log(e);
  supplierName.value = e.name;
  selectid.value = e.id;
};
const selectTo = () => {
  showInShop.value = false;
  form.value.supplierId = selectid.value;
  getappStockQuery(1);
};
const selectQx = () => {
  selectid.value = "";
  supplierName.value = "";
  showInShop.value = false;
  form.value.supplierId = selectid.value;
  getappStockQuery(1);
};

const ishowcamera = ref(false);
const scanFun = () => {
  // #ifdef H5
  uni.navigateTo({
    url:
      "/pages/code_sand/index?type=requiregoods&supplierId=" +
      (supplierId.value ? supplierId.value : ""),
  });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码
  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.keyword = res.result;
                  code.value = res.result;
                  getappStockQuery(1);
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keyword = res.result;
      code.value = res.result;
      getappStockQuery(1);
    },
  });
  // #endif
  // #ifdef APP-PLUS

  // if (uni.getSystemInfoSync().platform === "android") {
  //   console.log("android");
  //   const myScanCode = uni.requireNativePlugin("My-ScanCode");

  //   const options = {
  //     scanType: ["CODE_128", "QR_CODE"],
  //     prompt: "提示：将条形码/二维码图片对准扫描框即可自动扫描",
  //     locked: true,
  //   };
  //   console.log("sdasdas", myScanCode);
  //   myScanCode.scanCode(options, (res) => {
  //     if (res.success === "true") {
  //       form.value.keyword = res.result;

  //       code.value = res.result;
  //       uni.showToast({
  //         title: res.result,
  //         icon: "none",
  //       });
  //       getAppProductQuery(1);
  //     } else {
  //       uni.showToast({
  //         title: "扫码失败",
  //         icon: "none",
  //       });
  //     }
  //   });
  // } else {
  //   uni.scanCode({
  //     autoZoom: true,
  //     success: function (res) {
  //       console.log("条码类型：" + res.scanType);
  //       console.log("条码内容：" + res.result);
  //       form.value.keyword = res.result;
  //       code.value = res.result;
  //       getAppProductQuery(1);
  //     },
  //   });
  // }
  // #endif
  // #ifndef APP-PLUS || H5
  // uni.scanCode({
  //   autoZoom: true,
  //   success: function (res) {
  //     console.log("条码类型：" + res.scanType);
  //     console.log("条码内容：" + res.result);
  //     form.value.keyword = res.result;
  //     code.value = res.result;
  //     getAppProductQuery(1);
  //   },
  // });
  // #endif
};
</script>

<template>
  <topNav
    title="商品搜索"
    @scan="scanFun"
    @save="saveFun"
    rType="cancel"
    @search="searchFun"
    @blurfun="blurFun"
    @focusfun="focusFun"
    :IsSearch="true"
    :code="code"
  ></topNav>
  <view class="goods_form">
    <view
      class="content-top"
      :style="'top: calc( 88rpx + ' + topHeight + 'px);'"
    >
      <view class="content-top-shop" @click="shopSelectShow">
        <view>
          <text>按供应商</text>
          <!-- <view class="content-top-des">需提前2天提交</view> -->
        </view>
        <view class="content-top-shop-right">
          <view class="content-top-shop-right-icon">
            <text :class="supplierName ? 'new_select' : ''"
              >{{ supplierName ? supplierName : "请选择" }}
            </text>
            <up-icon name="arrow-right" color="#86909C" size="30rpx"></up-icon>
          </view>
          <!-- <up-icon name="arrow-right" color="#1679FB" size="30rpx"></up-icon> -->
        </view>
      </view>
      <view class="content-top-up">
        <text>常卖商品</text>
      </view>
    </view>

    <view
      class="scroll-Y-item"
      v-for="(item, index) in productData"
      :key="index"
      @click="onClickItem(item, index)"
    >
      <view class="scroll-item-left">
        <image :src="item.image" mode="scaleToFill" />
      </view>
      <view class="scroll-item-right">
        <view class="goods-item-title"> {{ item.name }} </view>
        <!-- <view class="goods-item-spec">
          条形码: {{ item.barCode ? item.barCode : "--" }}
        </view> -->
        <view class="goods-item-spec" v-if="!item.dhCode">
          商品码:{{ item.barCode ? item.barCode : "" }}</view
        >
        <view class="goods-item-spec" v-if="item.dhCode">
          称码:{{ item.dhCode ? item.dhCode : "" }}</view
        >
        <view class="goods-item-price">
          ¥{{ item.offerPrice }}
          {{ item.unit ? "/" + item.unit : "" }}
          <text class="goods-item-spec">库存:</text>
          {{ item.stockNum || 0 }}
        </view>
      </view>
      <view class="goods-item-num" @click.stop>
        <up-icon
          @click="onClickMinus(item, index)"
          name="plus-circle-fill"
          color="#1679fb"
          size="60rpx"
          v-if="item.transferNum <= 0"
        ></up-icon>
        <!-- -->
        <up-number-box
          v-if="item.transferNum > 0"
          buttonWidth="50rpx"
          buttonSize="50rpx"
          bgColor="#ffffff"
          :max="item.stockNum"
          v-model="item.transferNum"
          @change="(e) => valChange(item, index, e)"
          @blur="(e) => blurChange(item, index, e)"
          min="0"
        ></up-number-box>
        <view v-if="item.transferNum > item.stockNum" class="selectindex"
          >超出当前库存</view
        >
      </view>
    </view>
  </view>
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无商品 </view>
    </view>
  </view>
  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>

  <view style="height: 100rpx; width: 100%"></view>

  <view class="goods_bt" v-if="isShowBtn">
    <view class="goods_bt_to">
      <text
        >共<text class="blue">{{ selectNumList.length }}</text
        >款,<text class="blue">{{ goodsNum }}</text
        >件</text
      >
      <van-button class="val-button" type="primary" @click="goRecord"
        >确认</van-button
      >
    </view>
  </view>

  <up-modal
    :show="showMode"
    :title="
      selectItem.name +
      ', 库存超出' +
      (selectItem.stockNum - selectItem.transferNum)
    "
    width="500rpx"
    :content="''"
    @cancel="cancelFun"
    @confirm="confirmFun"
    confirmText="仍然调货"
    cancelText="取消"
    :showCancelButton="true"
  ></up-modal>

  <up-popup
    :show="showSelect"
    :closeable="true"
    mode="bottom"
    round="10"
    @close="showSelect = false"
  >
    <view class="popups">
      <view class="goods_p">
        <view class="goods">
          <view class="left">
            <image :src="selectItem.image" mode="scaleToFill" />
          </view>
          <view class="right">
            <view class="title">{{ selectItem.name }}</view>

            <view class="code" v-if="!selectItem.dhCode">
              商品码:{{
                selectItem.barCodeList && selectItem.barCodeList[0]
                  ? selectItem.barCodeList[0]
                  : selectItem.barCode
              }}</view
            >
            <view class="code" v-if="selectItem.dhCode">
              称码:{{ selectItem.dhCode ? selectItem.dhCode : "" }}</view
            >
            <view class="code">
              规格:{{ selectItem.spec ? selectItem.spec : "--" }}</view
            >

            <view class="price"
              >¥{{ selectItem.offerPrice }}/{{ selectItem.unit }}</view
            >
          </view>
        </view>
        <view class="num">
          <view class="left"> 数量 </view>
          <view class="right">
            <view class="num-box">
              <up-number-box
                min="0"
                v-model="selectItem.transferNum"
                @blur="(e) => blurChange(selectItem, 1, e)"
                @change="(e) => valChange(selectItem, 1, e)"
              ></up-number-box>
            </view>
          </view>
        </view>
      </view>
      <view class="goods_bt">
        <view class="goods_bt_to">
          <text
            >共<text class="blue">{{ selectNumList.length }}</text
            >款,<text class="blue">{{ goodsNum }}</text
            >件</text
          >
          <van-button class="val-button" type="primary" @click="goRecord"
            >确认</van-button
          >
        </view>
      </view>
    </view>
  </up-popup>

  <up-popup
    v-model:show="showInShop"
    round="10"
    @close="showInShop = false"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view class="popup-content">
      <view class="popup-content-title">
        <text>{{ "选择供应商" }}</text>
      </view>
      <view class="popup-content-list">
        <scroll-view
          scroll-y="true"
          class="scroll-Y"
          @scrolltoupper="upper"
          @scrolltolower="lower"
          @scroll="scroll"
        >
          <view
            class="scroll-to"
            v-for="(item, index) in ShopList"
            :key="index"
            @click="shopSelect(item, 1)"
          >
            <view
              class="scroll-to-title"
              :class="item.id == selectid ? 'scroll-to-title-sel' : ''"
            >
              <text>{{ item.name }}</text>
            </view>
            <up-icon
              v-if="item.id == selectid"
              name="checkbox-mark"
              color="#1679FB"
              size="40rpx"
            ></up-icon>
          </view>
        </scroll-view>
      </view>
      <view class="popup-content-btn">
        <up-button
          class="bt-qx"
          type="default"
          :plain="true"
          text="取消"
          @click="selectQx()"
        ></up-button>
        <up-button type="primary" @click="selectTo()" text="确定"></up-button>
      </view>
    </view>
  </up-popup>
  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
